import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import AutoImport from "unplugin-auto-import/vite";
// 组件按需引入
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
// 自动化路由
import Pages from "vite-plugin-pages";
// gzip压缩
import viteCompression from "vite-plugin-compression";

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, "");
  console.log(env);

  return {
    base: "./",
    plugins: [
      vue(),
      VueSetupExtend(),
      AutoImport({
        // dts: 'src/auto-import.d.ts',    // 路径下自动生成文件夹存放全局指令
        // imports: ["vue", "vue-router"],
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        // dts: 'src/components.d.ts',
        dirs: ["src/components"],
        deep: false,
        resolvers: [ElementPlusResolver()],
      }),
      Pages({
        dirs: [{ dir: "src/views", baseRoute: "" }],
        exclude: ["**/components/*.vue", "**/child/*.vue", "**/login/*.vue"], // 排除在外的目录，即不将所有 components 目录下的 .vue 文件生成路由
        importMode: "async",
      }),
      viteCompression(),
    ],
    css: {
      devSourcemap: true,
    },
    build: {
      outDir: "dist",
      // minify: "terser",
      // terserOptions: {
      // 	compress: {
      // 		drop_console: true,
      // 		drop_debugger: true
      // 	}
      // },
      rollupOptions: {
        input: path.resolve(__dirname, "index.html"),
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
          manualChunks: {
            // 每个 '键' 都表示一个分包块，'值' 包含列出的模块及其所有依赖项
            vue: ["vue", "vue-router", "pinia", "axios"],
            // editor: ['mavon-editor', '@kangc/v-md-editor']
          },
        },
      },
      sourcemap: true,
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
    },
    server: {
      host: true,
      hmr: {
        overlay: true,
        // 解决热更新不同步的问题
        port: 443,
      },
      port: 8888,
      proxy: {
        [env.VITE_BASE_API]: {
          target: env.VITE_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
  };
});
